/**
 * Created by gu on 2017/7/7.
 */

const sqlHelper = require("./sqlHelper");
const logger = require("../utils/logHelper").helper;

const daoMethod = {
    oneMethod: (sql, value) => {
        return new Promise((resolve, reject) => {
            sqlHelper.pool.getConnection((err, con) => {
                if (value) {
                    con.query(sql, value, (error, results) => {
                        logger.writeInfo(sql);
                        if (error) {
                            logger.writeErr(error);
                            con.release();
                            reject(error);
                        } else {
                            con.release();
                            resolve(results);
                        }
                    });
                } else {
                    con.query(sql, (error, results) => {
                        logger.writeInfo(sql);
                        if (error) {
                            logger.writeErr(error);
                            con.release();
                            reject(error);
                        } else {
                            con.release();
                            resolve(results);
                        }
                    });
                }
            });
        });
    },
    tran(func) {
        return new Promise((resolve, reject) => {
            sqlHelper.pool.getConnection((err, con) => {
                if (err) {
                    reject(err);
                }
                const tran = con.beginTransaction((err) => {
                    if (err) {
                        con.release();
                        reject(err);
                    }
                    func(con).then(() => {
                        tran.commit();
                        con.release();
                        resolve();
                    }).catch(() => {
                        tran.rollback(err => {
                            con.release();
                            if (err) {
                                reject();
                            }
                        })
                    });
                })
            })
        })

    }


};

module.exports = daoMethod;